﻿package com.wky.common.util;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.velocity.VelocityView;

public class VelocityViewWithHelper extends VelocityView {

    protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String nowType = response.getContentType();
        if (nowType != null && nowType.length() > 0) {
            nowType = this.getContentType();
            try {
                this.setContentType(response.getContentType());
                super.renderMergedTemplateModel(model, request, response);
            } finally {
                this.setContentType(nowType);
            }
        } else {
            super.renderMergedTemplateModel(model, request, response);
        }
    }

    /**
     * @see org.springframework.web.servlet.view.velocity.VelocityView#exposeHelpers(java.util.Map, javax.servlet.http.HttpServletRequest)
     */
    @SuppressWarnings("rawtypes")
	protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
    	model.put("request", request);
        super.exposeHelpers(model, request);
        if (null != HelperObjectCache.getHelperMap()) {
            for (Iterator<?> it = HelperObjectCache.getHelperMap().entrySet().iterator(); it.hasNext();) {
                Map.Entry me = (Map.Entry) it.next();
                if (model.containsKey(me.getKey()) && !HelperObjectCache.getAllowHelperOverride()) {
                    throw new ServletException("Cannot expose helper attribute '" + me.getKey() +
                        "' because of an existing model object of the same name");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Exposing helper attribute '" + me.getKey() +
                            "' with value [" + me.getValue() + "] to model");
                }
                model.put((String) me.getKey(), me.getValue());
            }
        }
    }

}

